package com.kly.test.function.home

import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.kly.test.base.BaseVMFragment
import com.kly.test.databinding.FragmentHomeBinding
import com.kly.test.function.home.viewmodel.HomeViewModel
import com.kly.test.function.home.viewmodel.HomeViewModelModelFactory
import androidx.lifecycle.Observer
import com.kly.test.base.adpater.isRefreshing

class HomeFragment : BaseVMFragment<FragmentHomeBinding, HomeViewModel>(
    FragmentHomeBinding::inflate,
    HomeViewModel::class.java
) {

    private val viewModelFactory by lazy { HomeViewModelModelFactory() } // 可以@Inject
    private val viewModel: HomeViewModel by viewModels { viewModelFactory }
    private val adapter by lazy { HomeDataListAdapter() }
    override fun initData() {
        initialViews()
        dispatchRequest()
        viewModel.dataAllList.observe(this, Observer {
            adapter.submitList(it)
        })

        viewModel.loading.observe(this, Observer {
            binding?.refreshLayout?.isRefreshing = it.isRefreshing()
        })
    }


    override fun initListener() {

    }

    private fun dispatchRequest() {
        viewModel.reqIndexList(true)
    }

    override fun onDestroyView() {
        binding?.recyclerView?.adapter = null
        adapter.setListener(null)
        binding?.refreshLayout?.setOnRefreshListener(null)
        super.onDestroyView()
    }

    private fun initialViews() {
        binding?.refreshLayout?.setOnRefreshListener {
            dispatchRequest()
        }
        binding?.recyclerView?.layoutManager = LinearLayoutManager(binding?.recyclerView?.context)
        binding?.recyclerView?.itemAnimator = null
        binding?.recyclerView?.adapter = adapter
    }
}